package cn.itsource.pethome.user.interceptors;

import cn.itsource.pethome.utils.RedisUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        //获取请求头中带过来的令牌
        String header = request.getHeader("U-TOKEN");
        if(StringUtils.isEmpty(header)){ //请求中没有携带这个请求头
            writeResponseMessage(response, "noToken");
            return false;
        }
        //请求中有次请求头，再与redis中的进行对比
        //将redis中的token取出来进行对比
        String loginUserStr = RedisUtils.INSTANCE.get(header);
        if(StringUtils.isEmpty(loginUserStr)){ //redis中的令牌已过期
            writeResponseMessage(response, "expireRedis");
            return false;
        }
        //有此令牌，且没过期
        //更新redis中的过期时间，因为用户还有操作，所以需要更新过期时间
        RedisUtils.INSTANCE.set(header, loginUserStr, 1*60*30);
        return true;
    }

    private void writeResponseMessage(HttpServletResponse response,String message){
        PrintWriter writer = null;
        try {
            response.setContentType("text/html;charset=utf-8");
            writer = response.getWriter();
            writer.write("{\"success\":false,\"message\":\""+message+"\"}");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            writer.close();
        }
    }
}
